package controller

import (
	"encoding/json"
	"errors"
)

type jsonApp struct {
	Base
}

func NewJSONApp() *jsonApp {
	return &jsonApp{}
}

// FormatJSON 格式化JSON字符串
func (a *jsonApp) FormatJSON(input string) (string, error) {
	var obj interface{}
	if err := json.Unmarshal([]byte(input), &obj); err != nil {
		return "", errors.New("无效的JSON: " + err.Error())
	}

	formatted, err := json.MarshalIndent(obj, "", "  ")
	if err != nil {
		return "", err
	}

	return string(formatted), nil
}

// ValidateJSON 校验JSON是否有效
func (a *jsonApp) ValidateJSON(input string) (string, error) {
	var obj interface{}
	if err := json.Unmarshal([]byte(input), &obj); err != nil {
		return "", errors.New("无效的JSON: " + err.Error())
	}
	return "JSON有效", nil
}

// MinifyJSON 压缩JSON
func (a *jsonApp) MinifyJSON(input string) (string, error) {
	var obj interface{}
	if err := json.Unmarshal([]byte(input), &obj); err != nil {
		return "", err
	}

	minified, err := json.Marshal(obj)
	if err != nil {
		return "", err
	}

	return string(minified), nil
}
